"""
UI工具模块
提供UI相关的工具函数
"""

import subprocess
import platform
from pathlib import Path

from PySide6.QtWidgets import QMessageBox
from PySide6.QtGui import QImage, QPixmap
from PIL import Image

from ..config.settings import AppConfig


class UIUtils:
    """UI工具类"""
    
    @staticmethod
    def open_directory(directory: str):
        """
        打开目录
        
        Args:
            directory (str): 目录路径
        """
        try:
            if platform.system() == "Windows":
                subprocess.run(["explorer", directory])
            elif platform.system() == "Darwin":
                subprocess.run(["open", directory])
            else:
                subprocess.run(["xdg-open", directory])
        except Exception as e:
            UIUtils.show_error(f"无法打开目录: {e}")
    
    @staticmethod
    def show_error(message: str, parent=None):
        """
        显示错误消息
        
        Args:
            message (str): 错误消息
            parent: 父窗口
        """
        QMessageBox.critical(parent, "错误", message)
    
    @staticmethod
    def show_info(message: str, parent=None):
        """
        显示信息消息
        
        Args:
            message (str): 信息消息
            parent: 父窗口
        """
        QMessageBox.information(parent, "信息", message)
    
    @staticmethod
    def show_warning(message: str, parent=None):
        """
        显示警告消息
        
        Args:
            message (str): 警告消息
            parent: 父窗口
        """
        QMessageBox.warning(parent, "警告", message)
    
    @staticmethod
    def pil_to_qimage(pil_image) -> QImage:
        """
        PIL图片转QImage
        
        Args:
            pil_image: PIL图片对象
            
        Returns:
            QImage: Qt图片对象
        """
        if pil_image.mode == "RGB":
            data = pil_image.tobytes()
            width, height = pil_image.size
            return QImage(data, width, height, width * 3, QImage.Format_RGB888)
        elif pil_image.mode == "RGBA":
            data = pil_image.tobytes()
            width, height = pil_image.size
            return QImage(data, width, height, width * 4, QImage.Format_RGBA8888)
        else:
            # 转换为RGB
            rgb_image = pil_image.convert("RGB")
            data = rgb_image.tobytes()
            width, height = rgb_image.size
            return QImage(data, width, height, width * 3, QImage.Format_RGB888)
    
    @staticmethod
    def pil_to_qpixmap(pil_image) -> QPixmap:
        """
        PIL图片转QPixmap
        
        Args:
            pil_image: PIL图片对象
            
        Returns:
            QPixmap: Qt图片对象
        """
        qimage = UIUtils.pil_to_qimage(pil_image)
        return QPixmap.fromImage(qimage)